package cn.hg.solon.youcan.system.provider;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.dromara.hutool.core.bean.BeanUtil;
import org.dromara.hutool.core.bean.copier.CopyOptions;
import org.dromara.hutool.core.collection.CollUtil;
import org.dromara.hutool.core.convert.Convert;
import org.dromara.hutool.core.date.DateUtil;
import org.dromara.hutool.core.text.CharSequenceUtil;
import org.dromara.hutool.core.text.StrValidator;
import org.dromara.hutool.core.util.ObjUtil;
import org.dromara.hutool.core.util.RandomUtil;
import org.dromara.hutool.db.PageResult;
import org.noear.solon.annotation.Component;
import org.noear.solon.data.annotation.Tran;

import com.easy.query.api4j.client.EasyQuery;
import com.easy.query.api4j.select.Queryable;
import com.easy.query.core.api.pagination.EasyPageResult;
import com.easy.query.solon.annotation.Db;

import cn.hg.solon.youcan.common.constant.AppConstants;
import cn.hg.solon.youcan.common.constant.WebConstants;
import cn.hg.solon.youcan.common.exception.ServiceException;
import cn.hg.solon.youcan.common.util.PasswordUtil;
import cn.hg.solon.youcan.system.entity.EqUser;
import cn.hg.solon.youcan.system.entity.EqUserRoleMapping;
import cn.hg.solon.youcan.system.entity.User;
import cn.hg.solon.youcan.system.service.UserService;

/**
 * @author 胡高
 */
@Component
public class EqUserProvider implements UserService {

    @Db
    private EasyQuery easyQuery;

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.UserService#assignRole(cn.hg.solon.youcan.system.entity.User, java.lang.Integer[])
     */
    @Tran
    @Override
    public void assignRole(User bean, List<Integer> roleIds) {
        /*
         * 删除所有关联角色
         * DELETE FROM sys_user_role WHERE user_id = ${bean.id}
         */
        this.easyQuery.deletable(EqUserRoleMapping.class)
        .where(w -> w.eq(EqUserRoleMapping::getUserId, bean.getId()))
        .allowDeleteStatement(true)
        .executeRows();

        /*
         * 重新建立用户角色映射
         */
        List<EqUserRoleMapping> beanList = new ArrayList<>();
        for (int id : roleIds) {
            EqUserRoleMapping urm = new EqUserRoleMapping();
            urm.setUserId(bean.getId());
            urm.setRoleId(id);

            beanList.add(urm);
        }

        if (CollUtil.isNotEmpty(beanList)) {
            this.easyQuery.insertable(beanList).executeRows();
        }
    }

    private Queryable<EqUser> buildQuery(Map<String, Object> map) {
        String word = (String)map.get("word");
        String status = (String)map.get("status");
        Integer deptId = (Integer)map.get("deptId");
        String sortField = (String)map.get("sortField");
        String sortType = (String)map.get("sortType");

        boolean customOrderBy = StrValidator.isNotBlank(sortField) && StrValidator.isNotBlank(sortType);

        // FROM sys_user AS t
        return this.easyQuery.queryable(EqUser.class)
            // WHERE t.`dept_id` = ${deptId} AND t.`status` = ${status}
            .where(w -> w.eq(ObjUtil.isNotNull(deptId), EqUser::getDeptId, deptId)
                .eq(StrValidator.isNotBlank(status), EqUser::getStatus, status)
                //  AND (t.`account` LIKE '%${word}%' OR t.`nickname` LIKE '%${word}%' OR t.`email` LIKE '%${word}%' OR t1.`phone` LIKE '%${word}%')
                .and(StrValidator.isNotBlank(word),
                    a -> a.like(EqUser::getAccount, word)
                    .or().like(EqUser::getNickname, word)
                    .or().like(EqUser::getEmail, word)
                    .or().like(EqUser::getPhone, word)))
            .orderBy(ob -> ob.sqlNativeSegment(customOrderBy ? CharSequenceUtil.toUnderlineCase(sortField) : "created_datetime"),
                (customOrderBy ? !CharSequenceUtil.equalsIgnoreCase(sortType, WebConstants.ORDER_DIRECTION_DESC) : Boolean.FALSE));
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.UserService#checkUnique(cn.hg.solon.youcan.system.entity.User)
     */
    @Override
    public boolean checkUnique(User bean) {
        // FROM sys_user AS t
        return !this.easyQuery.queryable(EqUser.class)
            // WHERE t.`account` = ${bean.account} AND t.`id` <> ${bean.id}
            .where(w -> w.eq(EqUser::getAccount, bean.getAccount()).ne(EqUser::getId, bean.getId()))
            .any();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.UserService#delete(java.util.List)
     */
    @Override
    public boolean delete(List<Integer> idList) {
        if (CollUtil.contains(idList, Integer.valueOf(1))) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "初始的 超级管理员 不允许删除！");
        }
        return this.easyQuery.deletable(EqUser.class)
            .where(w -> w.in(EqUser::getId, idList))
            .executeRows() > 0;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.UserService#get(java.lang.Integer)
     */
    @Override
    public User get(Integer id) {
        return this.easyQuery.queryable(EqUser.class).whereById(id).firstOrNull();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.UserService#getByAccount(java.lang.String)
     */
    @Override
    public User getByAccount(String account) {
        return this.easyQuery.queryable(EqUser.class).where(w -> w.eq(EqUser::getAccount, account)).firstOrNull();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.UserService#insert(cn.hg.solon.youcan.system.entity.User, java.util.List)
     */
    @Override
    public boolean insert(User bean, List<Integer> roleIdList) {
        if (!this.checkUnique(bean)) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "登录账号已经存在，请更换其它值！");
        }

        // 初始化密码
        bean.setSalt(RandomUtil.randomString(20));
        bean.setPassword(PasswordUtil.genSecretPassword(bean.getSalt(), bean.getPassword()));

        EqUser cloneBean = BeanUtil.copyProperties(bean, EqUser.class);

        // 注意：插入时使用的True，代表插入同时获取ID值填充到cloneBean
        boolean ret = this.easyQuery.insertable(cloneBean).executeRows(true) > 0;

        // 指派角色
        this.assignRole(cloneBean, roleIdList);

        return ret;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.UserService#listBy(java.util.Map)
     */
    @Override
    public List<? extends User> listBy(Map<String, Object> paraMap) {
        return this.buildQuery(paraMap).toList();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.UserService#pageBy(int, int, java.util.Map)
     */
    @Override
    public PageResult<EqUser> pageBy(int pageNumber, int pageSize, Map<String, Object> paraMap) {
        EasyPageResult<EqUser> pageList = this.buildQuery(paraMap).toPageResult(Convert.toLong(pageNumber), pageSize);

        PageResult<EqUser> result = new PageResult<>();
        result.addAll(pageList.getData());
        result.setTotal(Convert.toInt(pageList.getTotal()));

        return result;
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.UserService#resetPassword(cn.hg.solon.youcan.system.entity.User, java.lang.String, java.lang.String, cn.hg.solon.youcan.system.entity.User)
     */
    @Tran
    @Override
    public void resetPassword(User bean, String oldPassword, String newPassword, User editor) {
        if (!PasswordUtil.validatePassword(bean.getSalt(), oldPassword, bean.getPassword())) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "旧密码不正确！");
        }

        this.resetPassword(bean, newPassword, editor);
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.UserService#resetPassword(cn.hg.solon.youcan.system.entity.User, java.lang.String, cn.hg.solon.youcan.system.entity.User)
     */
    @Tran
    @Override
    public void resetPassword(User bean, String password, User editor) {
        bean.setPassword(PasswordUtil.genSecretPassword(bean.getSalt(), password));
        bean.setEditedDatetime(DateUtil.now());

        EqUser cloneBean = BeanUtil.copyProperties(bean, EqUser.class);

        this.easyQuery.updatable(cloneBean).executeRows();
    }

    /* (non-Javadoc)
     * @see cn.hg.solon.youcan.system.service.UserService#update(cn.hg.solon.youcan.system.entity.User)
     */
    @Override
    public boolean update(User bean) {
        if (!this.checkUnique(bean)) {
            throw new ServiceException(AppConstants.RETURN_CODE_VALUE_FAILED, "登录账号已经存在，请更换其它值！");
        }

        EqUser cloneBean = (EqUser)this.get(bean.getId());

        BeanUtil.copyProperties(bean, cloneBean, CopyOptions.of().setIgnoreNullValue(true));

        return this.easyQuery.updatable(cloneBean).executeRows() > 0;
    }
}
